package com.oman;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.Locale;

import com.oman.metadata.MediaMetaData;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.TextView;

public class VideoGallaryList extends Activity implements OnItemClickListener,OnScrollListener {
  private static String TAG = "VideoGallaryList";
  private VideoGalleryAdapter vgAdapter;
  private ArrayList<VideoViewInfo> videoRows;
  private ListTask vgTask;
  private AlertDialog mSelectDialog;
  private String mSelectedFilePath;
  private final int DIALOG_CHOICE = 1;

  //  Cursor cursor;


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.videogallary_main);

    ViewGroup mVG = (ViewGroup) getLayoutInflater().inflate(R.layout.videogallary_main, null);
    Log.d(TAG, "layout_Tag="+mVG.getTag());

    ListView listView = (ListView) this.findViewById(R.id.ListView);
    videoRows = new ArrayList<VideoViewInfo>();
    vgAdapter = new VideoGalleryAdapter(this, videoRows);

    listView.setAdapter(vgAdapter);
//    listView.setAdapter(new VideoGalleryAdapter(this, videoRows));
    listView.setOnItemClickListener(this);
  }

  @Override
protected void onResume() {
      Log.d(TAG, "onResume()");
//      if(vgTask == null) {
//          vgTask = new ListTask(vgAdapter);
//          vgTask.execute();
//      }
//      if(vgAdapter.isEmpty()) {
          vgAdapter.setcleanObject();
          vgAdapter.setObjects();
//      }

    super.onResume();
}


@Override
protected void onPause() {
    // TODO Auto-generated method stub
    Log.d(TAG, "onPause()");
    super.onPause();
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    Log.d(TAG, "onDistroy");
//    The content of the adapter has changed but ListView did not receive a notification.
    vgAdapter.notifyDataSetChanged();
    super.onDestroy();
}

@Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
      Log.e("", "onItemClick");
    VideoViewInfo vInfor = videoRows.get(position);
    String videoFilePath = vInfor.filePath;
    mSelectedFilePath = videoFilePath;

    showDialog(DIALOG_CHOICE);
  }

final String items[] = { "TRIM", "TRIM_SHARE","MediaMetaData"};
@Override
protected Dialog onCreateDialog(int id, Bundle args) {
    // TODO Auto-generated method stub
    switch(id) {
    case DIALOG_CHOICE:
        return new AlertDialog.Builder(this)
        .setTitle("Select Run")
        .setItems(items,
                new DialogInterface.OnClickListener() {
                    File newFile = new File(mSelectedFilePath);
                    Intent intent;

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        switch(which) {
                        case 0:
                            intent = new Intent("android.intent.action.TRIM");
                            intent.putExtra("uri", Uri.fromFile(newFile));
                            startActivityForResult(intent, 100);

                            removeDialog(DIALOG_CHOICE);
                            break;
                        case 1:
                            intent = new Intent("android.intent.action.TRIM_SHARE");
                            intent.putExtra("uri", Uri.fromFile(newFile));
                            startActivityForResult(intent, 100);

                            removeDialog(DIALOG_CHOICE);
                            break;
                        case 2:
                            intent= new Intent(getApplicationContext(), MediaMetaData.class);
                            intent.putExtra("uri", Uri.fromFile(newFile));
                            startActivityForResult(intent, 100);
//                            startActivity(intent);
                            removeDialog(DIALOG_CHOICE);
                            break;
                        }
                    }
                })
         .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                removeDialog(DIALOG_CHOICE);
            }
        }).create();
    }
    return null;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    Log.e(TAG, "requestCode="+requestCode+"resultCode="+resultCode);
        if (requestCode == 100  && data != null) {
            Uri selectedVideo = data.getData();
            Log.e(TAG, "path="+selectedVideo.getPath());
        }

    super.onActivityResult(requestCode, resultCode, data);
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
    // TODO Auto-generated method stub
    }

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
        int visibleItemCount, int totalItemCount) {
    Log.e(TAG, "onScroll");
    // TODO Auto-generated method stub
    }
}

class VideoViewInfo {
    String filePath;
    String mimeType;
    String thumbPath;
    String title;
    String size;
    String duraion;
    Bitmap thumbImage;
  }

class VideoGalleryAdapter extends BaseAdapter {
      private static String TAG = "VideoGallaryList";

      private final Context context;
      private final ArrayList<VideoViewInfo> videoItems;

      LayoutInflater inflater;

      public VideoGalleryAdapter(Context _context, ArrayList<VideoViewInfo> _items) {
        context = _context;
        videoItems = _items;

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      }

      public void setObjects() {

          String[] mediaColumns = {
                  MediaStore.Video.Media._ID,
                  MediaStore.Video.Media.DATA,
                  MediaStore.Video.Media.TITLE,
                  MediaStore.Video.Media.MIME_TYPE,
                  MediaStore.Video.Media.SIZE,
                  MediaStore.Video.Media.DURATION};

          Cursor cursor = ((Activity) context).managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
              mediaColumns, null, null, null);

          if (cursor.moveToFirst()) {
            do {

              VideoViewInfo newVVI = new VideoViewInfo();

              newVVI.filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
              newVVI.title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
              newVVI.mimeType = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
              newVVI.size = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
              newVVI.duraion = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));

              videoItems.add(newVVI);
            } while (cursor.moveToNext());
          }
      }
      public void setcleanObject() {
          this.videoItems.clear();
      }

      public void setObject(int position, VideoViewInfo vInfo) {
          videoItems.set(position, vInfo);
      }

      @Override
      public int getCount() {
        return videoItems.size();
      }

      @Override
      public Object getItem(int position) {
        return videoItems.get(position);
      }

      @Override
      public long getItemId(int position) {
        return position;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
//          Log.d(TAG, "getView position="+position);
          View videoRow = convertView;

          if(videoRow == null) {
             videoRow = inflater.inflate(R.layout.row, null);
             ViewHolder viewHodler = new ViewHolder();

             viewHodler.thumView = (ImageView) videoRow.findViewById(R.id.ImageView);
             viewHodler.videoTitle = (TextView) videoRow.findViewById(R.id.titleView);
             viewHodler.videoSize = (TextView) videoRow.findViewById(R.id.sizeView);
             viewHodler.duration = (TextView) videoRow.findViewById(R.id.durationView);
             viewHodler.filePath = (TextView) videoRow.findViewById(R.id.filepathView);

             videoRow.setTag(viewHodler);
          }

          //set row backGround.
          if( position %2 == 0) {
              videoRow.setBackgroundResource(R.drawable.event_row);
          } else {
              videoRow.setBackgroundResource(R.drawable.odd_row);
          }

          ViewHolder holder = (ViewHolder) videoRow.getTag();

          if(videoItems.get(position).filePath != null){
            if(videoItems.get(position).thumbImage == null){
//                Log.i("getView", "start ImageTask for get ImageBitmap");
//                thumView.setBackgroundResource(R.drawable.no_item_video);

                ImageTask imagetask = new ImageTask(holder.thumView);
                imagetask.execute(videoItems.get(position));

            } else {
                holder.thumView.setScaleType(ScaleType.FIT_XY);
                holder.thumView.setImageBitmap(videoItems.get(position).thumbImage);
            }

            holder.videoTitle.setText(videoItems.get(position).title);
            holder.videoSize.setText(readableFileSize(Long.parseLong(videoItems.get(position).size)));
//            holder.duration.setText(stringForTime(Integer.parseInt(videoItems.get(position).duraion)));
            int iDuration = 0;
            if(videoItems.get(position).duraion != null) {
                iDuration = Integer.parseInt(videoItems.get(position).duraion);
            }

            String sDuration = stringForTime(iDuration);
            holder.duration.setText(sDuration);
            holder.filePath.setText(videoItems.get(position).filePath);
        }


        return videoRow;
      }

      private static class ViewHolder{
          ImageView thumView;
          TextView videoTitle;
          TextView videoSize;
          TextView duration;
          TextView filePath;
      }

      private String stringForTime(int timeMs) {
          if (timeMs < 0) {
              return "";
          }
          int totalSeconds = timeMs / 1000;

          int seconds = totalSeconds % 60;
          int minutes = (totalSeconds / 60) % 60;
          int hours   = totalSeconds / 3600;

          StringBuilder mFormatBuilder = new StringBuilder();
          Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

          mFormatBuilder.setLength(0);
          return mFormatter.format("%02d:%02d:%02d", hours, minutes, seconds).toString();
      }

      private String readableFileSize(long size) {
          if(size <= 0) return "0";
          final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
          int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
          return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
      }
    }

class ListTask extends AsyncTask<Void, Integer,ArrayList<VideoViewInfo>> {
    private final VideoGalleryAdapter adapter;

    public ListTask(VideoGalleryAdapter _adapter) {
        this.adapter = _adapter;
    }

    @Override
    protected void onPreExecute() {
        this.adapter.notifyDataSetChanged();
        super.onPreExecute();
    }
    @Override
    protected ArrayList<VideoViewInfo> doInBackground(Void... params) {
        this.adapter.setObjects();
        return null;
    }

}

class ImageTask extends AsyncTask<VideoViewInfo, Void, Bitmap> {
    private static String TAG = "VideoGallaryList";

    private VideoViewInfo mVideoInfo;
    private final WeakReference<ImageView> imageViewReference;

    public ImageTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    protected Bitmap doInBackground(VideoViewInfo... params) {
//        Log.d(TAG, "doInBackground");
        mVideoInfo = params[0];

        mVideoInfo.thumbImage =ThumbnailUtils.createVideoThumbnail(mVideoInfo.filePath, MediaStore.Video.Thumbnails.MINI_KIND);
        return mVideoInfo.thumbImage;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if(this.isCancelled()) {
            bitmap = null;
        }
        if(imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if(imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }

}